package com.haoxuer.discover.plug.weiapp;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.haoxuer.discover.plug.api.ProxyPlugin;
import com.haoxuer.discover.plug.data.entity.PluginConfig;
import com.haoxuer.discover.rest.base.ResponseObject;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Component("weiAppPushPlug")
public class WeiAppPushPlug extends ProxyPlugin {

  private Logger logger = LoggerFactory.getLogger(WeiAppPushPlug.class);

  @Override
  public ResponseObject handle(Map<String, String> params) {
    ResponseObject result = new ResponseObject();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String appId = pluginConfig.getAttribute("appId");
      String secret = pluginConfig.getAttribute("secret");
      WxMaService service = new WxMaServiceImpl();
      WxMaInMemoryConfig config = new WxMaInMemoryConfig();
      config.setAppid(appId);
      config.setSecret(secret);
      service.setWxMaConfig(config);
      WxMaMsgService maMsgService = service.getMsgService();
      WxMaTemplateMessage template = new WxMaTemplateMessage();
      template.setFormId(params.get("FormId"));
      template.setTemplateId(params.get("TemplateId"));
      template.setToUser(params.get("User"));
      List<WxMaTemplateData> datas = new ArrayList<>();

      Set<String> sets = params.keySet();
      for (String key : sets) {
        if (key.startsWith("keyword")) {
          WxMaTemplateData data1 = new WxMaTemplateData();
          data1.setName(key);
          data1.setValue(params.get(key));
          datas.add(data1);
        }
      }
      template.setData(datas);
      template.setPage(params.get("page"));
      try {
        maMsgService.sendTemplateMsg(template);
      } catch (WxErrorException e) {
        logger.error("发送消息失败", e);
      }
    }
    return result;
  }

  @Override
  public String catalog() {
    return "weiapp";
  }

  @Override
  public String viewName() {
    return "weiapp";
  }

  @Override
  public String getName() {
    return "微信小程序推送服务";
  }

  @Override
  public String getVersion() {
    return "1.0.1";
  }


}
